import { ref, onMounted, onUnmounted, Ref, nextTick } from 'vue'

export const useContextMenu = (
  containerRef: Ref<HTMLDivElement | undefined>
) => {
  const x = ref(0)
  const y = ref(0)
  const showMenu = ref(false)

  const handleContextMenu = (e: MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (!containerRef.value) return

    x.value = e.clientX
    y.value = e.clientY
    showMenu.value = true
  }

  const closeMenu = () => {
    showMenu.value = false
  }

  onMounted(() => {
    containerRef.value?.addEventListener('contextmenu', handleContextMenu)
    window.addEventListener('click', closeMenu, true)
    window.addEventListener('contextmenu', closeMenu, true)
  })

  onUnmounted(() => {
    containerRef.value?.removeEventListener('contextmenu', handleContextMenu)
    window.removeEventListener('click', closeMenu, true)
    window.removeEventListener('contextmenu', closeMenu, true)
  })

  return {
    x,
    y,
    showMenu
  }
}
